package com.leco.exam.topic.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leco.exam.common.biz.exception.ExamException;
import com.leco.exam.topic.biz.dao.QuestionDao;
import com.leco.exam.topic.biz.entity.Question;
import com.leco.exam.topic.biz.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author greg
 * @version 2022/9/8
 **/
@Slf4j
@Service
public class QuestionServiceImpl implements QuestionService {
    @Resource
    private QuestionDao questionDao;

    @Override
    @Cacheable(value = "question", key = "#id")
    public Question getById(Integer id) {
        log.info("call QuestionServiceImpl.getById::id={}", id);
        return questionDao.selectById(id);
    }

    @Override
    @Cacheable(value = "questionList", key = "#topicId")
    public List<Question> listByTopicId(Integer topicId) {
        if (topicId == null) {
            throw new ExamException("topicId不可为空");
        }
        return questionDao.selectList(Wrappers.lambdaQuery(Question.class)
                .eq(Question::getTopicId, topicId)
        );
    }

    @Override
    @CacheEvict(value = "questionList", key = "#question.topicId")
    public Integer addQuestion(Question question) {
        return questionDao.insert(question);
    }
}
